package com.zhoufy.tomcat.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * Created with IntelliJ IDEA by ChouFy on 2020-03-27.
 * <p>
 * 封装response对象 需要依赖于OutputStream
 *
 * @author zhoufy
 */
public class Response {

    private OutputStream outputStream;

    public Response() {
    }

    public Response(OutputStream outputStream) {
        this.outputStream = outputStream;
    }

    /**
     *   输出指定字符串
     */
    public void output(String content) throws IOException {
        outputStream.write(content.getBytes());
        outputStream.flush();
    }

    /**
     * @param path url，随后要根据url来获取到静态资源的绝对路径，进一步根据绝对路径读取该静态资源文件，
     *             最终通过输出流输出
     */
    public void outputHTML(String path) throws IOException {
        // 获取静态资源文件的绝对路径
        String absoluteResourcePath = StaticResourcesUtil.getAbsolutePath(path);

        // 输入静态资源
        File file = new File(absoluteResourcePath);
        if(file.exists() && file.isFile()){
            //  输出静态资源
            InputStream fileInputStream = new FileInputStream(file);
            StaticResourcesUtil.outputStaticResource(fileInputStream, outputStream);
            fileInputStream.close();
        } else {
            output(HttpProtocolUtil.getHttpHeader404());
        }
    }
}
